<?php
namespace Api\Controller;

use Admin\Api\OrdersPaycodeApi;
use Admin\Api\UidMgroupApi;
use Shop\Api\AddressApi;
use Shop\Api\HasIdcodeApi;
use Shop\Api\MemberConfigApi;
use Shop\Api\OrderRefundApi;
use Shop\Api\OrdersApi;
use Shop\Api\OrdersExpressApi;
use Shop\Api\OrdersInfoViewApi;
use Shop\Api\OrderStatusApi;
use Shop\Api\OrderWithItemsApi;
use Shop\Api\OrderWithStoresApi;
use Shop\Api\ShoppingCartApi;
use Shop\Api\OrdersItemApi;
use Shop\Model\OrdersModel;

/**
 * Created by PhpStorm.
 * User: an
 * Date: 2015/8/5
 * Time: 16:45
 */

class OrdersController extends ApiController{

    /**
     * 订单支付
     */
    public function pay(){

        addLog("Orders/pay",$_GET,$_POST,"应用".$this->client_id.",调用单个订单支付接口",false);

        $uid = $this->_post("uid",0,"缺少用户ID");
        $order_id = $this->_post("order_id",0,"缺少订单ID");
        $pay_type = $this->_post("pay_type",1);

        $map = array(
            'id'=>$order_id,
            'uid'=>$uid,
        );

        $result = apiCall(OrdersApi::GET_INFO,array($map));

        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
            $this->apiReturnErr($result['info']);
        }

        if(is_null($result['info'])){
            $this->apiReturnErr("订单ID非法!");
        }

        $order = $result['info'];

        $pay_code = $order['order_code'].';';

        $now  = time();
        $total_price = $order['price'];

        //5. 返回支付编号,用这个支付编号来生成支付信息
        $ordersPayCode = array(
            'order_content'=>$pay_code,
            'create_time'=>$now,
            'pay_type'=>$pay_type,
            'pay_money'=>$total_price,
            'uid'=>$uid,
        );

        $result = apiCall(OrdersPaycodeApi::ADD,array($ordersPayCode));
        if($result['status']){
            $pay_id = $result['info'];

            $info = $this->getPayReturnInfo($pay_id,$uid,$total_price);

            $this->apiReturnSuc($info);
        }else{
            $this->apiReturnErr("支付信息生成失败!");
        }

    }



    /**
     * 添加订单（唯一订单添加接口）
     * UID,idcode(别人的),cartids 购物车里的商品id
     * from,note,cartids,
     * addr_id 收货地址ID
     */
    public function  add(){

        addLog("Orders/add",$_GET,$_POST,"应用".$this->client_id.",调用添加订单接口",false);

        //购买人的用户ID
        $uid = $this->_post("uid",0,"缺少用户ID");
        $idcode = $this->_post("idcode",""); //优惠码
        $selfCoupon =  $this->getSelfCoupon($uid);//自身的优惠信息
        $otherCoupon =  $this->getOtherCoupon($idcode,$uid);//其它人的优惠信息
        $cart_ids = $this->_post("cart_ids","","购物车信息缺失");
        $addr_id = $this->_post("addr_id","","缺失收货地址"); //收货地址ID
        $from = $this->_post("from",""); //订单来源
        $pay_type = $this->_post("payType",""); //支付类型
        if(empty($pay_type)){
            $pay_type = $this->_post("pay_type",""); //支付类型
        }
        if(empty($pay_type)) {
            $pay_type = 1;
        }
        if($pay_type != 1 || $pay_type != 2){
            $this->error("支付方式不支持!");
        }
        $note = $this->_post("note",""); //备注

        addLog("Orders/add buy_cart_id",$cart_ids,$addr_id,'[调试]',true);

        //1.  收货地址
        $map = array(
            'id'=>$addr_id,
        );

        if($addr_id > 0){

        }

        $result = apiCall(AddressApi::GET_INFO,array($map));

        addLog("Orders/add buy_cart_id",$result,$addr_id,'[调试]',true);

        $this->checkApiCallResult($result,true,"收货地址缺失!");
        $address = $result['info'];
        unset($address['id']);

        if(empty($address)){
            $this->apiReturnErr("收货地址缺失");
        }
        if(empty($address['id_card'])){
//            $this->apiReturnErr("身份证必须!");
        }


        $entity = array(

        );

        //合并收货地址
        $entity = array_merge($entity,$address);


        //2. 购物车信息
        $map = array(
            'uid'=>$uid,
            'id'=>array('in',$cart_ids),
        );

        addLog("Orders/add map",$map,'','[调试]',true);
        $result = apiCall(ShoppingCartApi::QUERY_WITH_STORE_INFO,array($map));

        addLog("Orders/add map",$map,'','[调试]',true);
        $this->checkApiCallResult($result,true,"购物车里没有商品哦!");
        $cart = $result['info'];

        $cart = $this->groupByStore($cart);
        //1. 本商城生成的支付编号
        $payCode = "";
        $total_price = 0;
        //3. 对每个店铺生成一张订单
        foreach($cart as $key=>$vo){
            //1. 备注
            $entity['note'] = $note;
            $entity['uid'] = $uid;
            $entity['order_code'] = getOrderid($uid);
            $entity['storeid'] = $key;
            $entity['idcode'] = $idcode;
            $entity['from'] = $from;
            $entity['pay_type'] = $pay_type;
            $entity['id_card'] = $address['id_card'];

            $calInfo = $this->calPrice($address,$vo,$selfCoupon,$otherCoupon);

            $entity = array_merge($entity,$calInfo);

            if($entity['count'] > 1 && $entity['price'] > 1000){
                $this->apiReturnErr("海关规定购买多件的总价（不含税）不能超过1000元!");
            }



            addLog("Api/Orders/Add" , $entity , $address , '[订单添加对象]' , true);
            $result = apiCall(OrdersApi::ADD_ORDER,array($entity));

            if($result['status']){

                $payCode .= $result['info'].";";
                $total_price = $total_price + $entity['price'];
                if(!empty($idcode)){
                    $this->addIDCode($idcode,$uid);
                }
            }

        }



        addLog("Api/Orders/add 删除购物车数据",$payCode,$total_price,"[调试]",true);

        //4. 添加到订单之后，就该删除购物车的数据
        $this->deleteFromShoppingCart($uid,$cart_ids);
        $now = time();
        //5. 返回支付编号,用这个支付编号来生成支付信息
        $ordersPayCode = array(
            'order_content'=>$payCode,
            'create_time'=>$now,
            'pay_type'=>$pay_type,
            'pay_money'=>$total_price,
            'uid'=>$uid,
        );

        $result = apiCall(OrdersPaycodeApi::ADD,array($ordersPayCode));
        if($result['status']){
            $pay_id = $result['info'];

            $info = $this->getPayReturnInfo($pay_id,$uid,$total_price);

            $this->apiReturnSuc($info);
        }else{
            $this->apiReturnErr("支付信息生成失败!");
        }

    }



    //***************优惠信息***************************

    private function addIDCode($idcode,$uid){
        $result = apiCall(HasIdcodeApi::GET_INFO,array(array('idcode'=>$idcode,'uid'=>$uid)));
        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
        }
        if(is_array($result['info'])){
            return;
        }
        //使用了IDCode，则加入历史纪录
        $idcodeEntity = array(
            'uid'=>$uid,
            'idcode'=>$idcode,
            'get_time'=>NOW_TIME,
            'status'=>1,
            'begin_time'=>0,
            'end_time'=>0,
        );

        $result = apiCall(HasIdcodeApi::ADD,array($idcodeEntity));
        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
        }

    }

    private function getPayReturnInfo($pay_id,$uid,$total_price){
        $now = time();

        $code = 'T'.$now.'U'.$uid.'P'.$pay_id;
        $name = '订单'.$code;
        $desc = $name;
        //保留2位
        $total_price = round($total_price,2);
        $info = array(
            'code'=>$code,
            'name'=>$name,
            'desc'=>$desc,
            //@author 老胖子-何必都 <hebiduhebi@126.com>
            //转换成字符串，否则IOS端解析成数字类型时精度会有问题，比如74.10 被解析成74.09999999999999,从而导致APP端验证失败!
            'total_price'=>strval($total_price)
        );

        $encode = urlencode($code.$name.$desc.$total_price);
        $encode = md5(strtolower($encode));

        $info['key'] = pay_encrypt_md5($encode);
        $info['show_url'] = C('SITE_URL');

        return $info;
    }

    /**
     * 从购物车中删除
     * @author 老胖子-何必都 <hebiduhebi@126.com>
     * @param $uid
     * @param $cart_ids
     */
    private function deleteFromShoppingCart($uid,$cart_ids){
        $map = array(
            'uid'=>$uid,
            'id'=>array('in',$cart_ids),
        );

        $result = apiCall(ShoppingCartApi::DELETE,array($map));
        if(!$result['status']){
            LogRecord($result['info'],__FILE__.__LINE__);
        }
    }

    /**
     * 获取优惠比例
     * @author 老胖子-何必都 <hebiduhebi@126.com>
     * @param $store_id
     * @param $coupons
     * @return bool
     */
    private function getDiscountRatio($store_id,$coupons){

        if(empty($coupons)){
            return false;
        }

        foreach($coupons as $vo){
            if($store_id == $vo['storeuid']){
                return $vo;
            }
        }
        return false;
    }

    /**
     * 计算单个订单里的金额
     * @param $address array 收货地址，计算运费用
     * @param $items   array  购物的商品信息，购物车项
     * @param $selfCoupon  array 自己的优惠信息
     * @param $otherCoupon array  其它人的优惠信息，自己可以用，填了优惠码,也可空
     * @return array
     */
    private function calPrice($address,$items,$selfCoupon,$otherCoupon){
        $entity = array();
        $entity['count'] = 0;       //总件数
        $entity['price'] = 0;       //应付金额
        $entity['post_price'] = 0; //运费
        $entity['discount_money'] = 0; //折扣金额数
        $entity['brokerage_ratio'] = 0; //返佣比例
        $entity['tax_amount'] = 0; //税款
        $entity['goods_amount'] = 0; //货款＝商品金额＊数量 总和
        $entity['items']  = array();
        foreach($items as $item){
            //
            $self = $this->getDiscountRatio($item['store_creator'],$selfCoupon);
            $other = $this->getDiscountRatio($item['store_creator'],$otherCoupon);

            $discount_radio = $self['discount_ratio'];
            addLog("Api/Orders/add",$self,$other,"[调试是否使用了其他人的优惠码]",true);
            if(!empty($other)){
                $entity['brokerage_ratio'] = $other['commission_ratio'];
                $discount_radio = $discount_radio + $other['discount_ratio'];
            }

            $item['discount_radio'] = $discount_radio;
            $cnt = intval($item['count']);
            $entity['count'] = $entity['count'] + $cnt;
            //3. 折扣价格
            $discount_price = round($item['price']*$discount_radio,2);
            //1. 该商品使用优惠码之后的价格,保留2位小数点，防止验证失败
            $price = $cnt * ($item['price'] - $discount_price);
            //2. 计算该商品的运费
            $post_price = $this->getPostPrice($item['template_id'],$address);

            //3. 税款
            $taxAmount =   $cnt * $item['price'] * $item['taxrate'];

            //4. 货款
            $goodsAmount = $cnt * $item['price'];

            if($price < 0 ){
                LogRecord("商品优惠金额不能为负!",__FILE__.__LINE__);
                $this->error("服务器计算商品价格出错!");
            }
            //1. 优惠金额
            $entity['discount_money'] = $entity['discount_money'] + $cnt*$discount_price;//折扣
            $entity['tax_amount'] = $entity['tax_amount'] + $taxAmount; //税款
            $entity['goods_amount'] = $entity['goods_amount'] + $goodsAmount; //货款
            $entity['post_price'] =  $entity['post_price'] + $post_price; //运费
            $entity['price'] = $entity['price'] + $price;

            $duty_free_price = C('DUTY_FREE_PRICE');
            $duty_free_price = floatval($duty_free_price);
            if($taxAmount > $duty_free_price){
                $entity['price'] =  $entity['price'] + $taxAmount;
            }

            array_push($entity['items'],$item);

        }

        addLog("CalDiscountMoney 计算的应付金额，不含运费",$entity,"","[调试]",true);
        return $entity;
    }


    /**
     * 获取运费金额
     */
    private function getPostPrice($template_id,$address){
        //TODO: 设置运费信息

        return 0;
    }

    //对商品信息进行分组
    private function groupByStore($cart){
        $new_cart = array();

        foreach($cart as $vo){
            $store_id = $vo['store_id'];
            if(!isset($new_cart[$store_id])){
                $new_cart[$store_id] = array();
            }
            array_push($new_cart[$store_id],$vo);
        }
        return $new_cart;
    }


    private function getOtherCoupon($idcode,$self_uid){

        $result = apiCall(MemberConfigApi::GET_INFO,array(array('idcode'=>$idcode)));

        $this->checkApiCallResult($result,false);
        if(is_null($result['info'])){
            return array();
        }

        $uid =  $result['info']['uid'];
        if($uid == $self_uid){
            //不能使用自己的优惠码
            return array();
        }

        $result = apiCall(UidMgroupApi::QUERY_WITH_UID,array($uid));

        $this->checkApiCallResult($result,false);

        return $result['info'];
    }

    private function getSelfCoupon($uid){

        $result = apiCall(UidMgroupApi::QUERY_WITH_UID,array($uid));

        $this->checkApiCallResult($result,true,"无法获取您的优惠信息!");

        return $result['info'];
    }

    //*****************************************************


    /**
     * 获取订单编号
     */
    function getOrderid($uid){

        list($usec, $sec) = explode(" ", microtime());
        $usec = str_pad(floor($usec*1000000), 6,STR_PAD_RIGHT);

        srand($usec);

        $rand = rand(100, 999);

        $orderID = date("yzHis",$sec).$usec;

        return 'A'.$orderID.$rand.get_36HEX($uid);

    }
	
	
	/**
	 * 取消订单
	 */
	public function qxorder(){
		$notes = "应用".$this->client_id.",调用修改订单接口";
        addLog("Orders/qxorder",$_GET,$_POST,$notes);
        //首先接收用户ID，
        $uid=$this->_post("uid",0,'用户ID缺失');

		$order_code=$this->_post('order_code',0,'订单编号缺失');

        $result = apiCall(OrderStatusApi::CANCEL,array($order_code,false,$uid));

		if($result['status']){
			$this->apiReturnSuc('取消成功!');
		}else{
			$this->apiReturnErr('取消失败!');
		}
		
	}
	
	
	/*
	 * 确认收货
	 * */
	public function sureorder(){
		$notes = "应用".$this->client_id.",调用修改订单接口";
        addLog("Orders/sureorder",$_GET,$_POST,$notes);
        //首先接收用户ID，
        $uid=$this->_post("uid",0,'用户ID缺失');

        $order_code=$this->_post('order_code',0,'订单编号缺失');

        $result = apiCall(OrderStatusApi::CONFIRM_RECEIVE,array($order_code,false,$uid));

		if($result['status']){
			$this->apiReturnSuc('成功确认收货!');
		}else{
			$this->apiReturnErr('确认收货失败!'.$result['info']);
		}
		
	}
	
	/*
	 * 退货
	 * */
	public function returnorder(){
		$notes = "应用".$this->client_id.",调用新增退货接口";
        addLog("OrderRefund/add",$_GET,$_POST,$notes);

        $uid = $this->_post("uid",0,"缺少用户ID");

		$order_code = $this->_post('order_code','',"无法获取订单!");

		$text=$this->_post('reason','无');
		$entity = array('create_time'=>time(),'reason'=>$text,'valid_status'=>0,'reply_msg'=>'','order_code'=>$order_code);
		$result = apiCall(OrderRefundApi::ADD,array($entity));
		if($result['status']){


			$this->apiReturnSuc('申请退货成功,等待客服反馈!');
		}else{
			$this->apiReturnErr('申请退货失败!');
		}
	}


    /**
     * 查询订单列表
     */
    public function query(){
        $notes = "应用".$this->client_id.",调用查询订单接口";
        addLog("Orders/query",$_GET,$_POST,$notes);
        //首先接收用户ID，根据用户ID去查询他的所有订单，当然要分页
        $uid= $this->_post("uid",0,"uid缺失!");
        $status = $this->_post("status",'');



        if($uid==0){
            $this->apiReturnErr("缺少用户ID");
        }

        $map=array(
            'uid'=>$uid,
        );

        if(!empty($status)){
            $map = array_merge($map,$this->getQueryStatus($status));
        }

        $curPage = $this->_post("curpage",1);
        $curPage = intval($curPage);
        $pageSize = $this->_post("pagesize",10);
        $pageSize = intval($pageSize);

        if($curPage < 1){
            $curPage = 1;
        }
        if($pageSize > 30){
            $pageSize = 30;
        }
        if($pageSize <= 0){
            $pageSize = 10;
        }

        $page = array('curpage'=>$curPage,'size'=>$pageSize); //分页

        $order = "updatetime desc";

        $result = apiCall(OrderWithStoresApi::QUERY_WITH_COUNT,array($map,$page,$order));

        $orderList = $result['info']['list'];
        $count = $result['info']['count'];

        if(empty($orderList) ||$count == 0){
            $this->apiReturnSuc("");
        }

        $mapItem = $this->getMapFromResult($orderList);

        $result = apiCall(OrdersItemApi::QUERY_NO_PAGING,array($mapItem));

        if($result['status']){
            $list =  $this->combine($orderList,$result['info']);
            $return = array('total'=>$count,'list'=>$list);
            $return['curpage'] = $curPage;
            $return['pagesize'] = $pageSize;
            $this->apiReturnSuc($return);
        }else{
            $this->apiReturnErr("您还没有订单，快去购物吧");
        }
    }

    /**
     * 将此处查询状态
     * 转换为订单状态或支付状态
     * @param $status
     * @return array
     */
    private function getQueryStatus($status){
        $map = array();
        switch($status){
            case 0:
                break;
            case 1:
                $map['pay_status'] = OrdersModel::ORDER_TOBE_PAID;
                $map['order_status'] = OrdersModel::ORDER_TOBE_CONFIRMED;
                break;
            case 2:
                $map['pay_status'] = OrdersModel::ORDER_PAID;
                $map['order_status'] = OrdersModel::ORDER_TOBE_CONFIRMED;
                break;
            case 3:

                $map['order_status'] = OrdersModel::ORDER_SHIPPED;
                break;
            case 4:
                $map['order_status'] = OrdersModel::ORDER_RECEIPT_OF_GOODS;
                break;
            default:
                break;
        }
        return $map;
    }

    /**
     * Convert
     * @param $order_list
     * @return mixed
     */
    private function combine($orderList,$itemList){
        foreach($itemList as $vo){
            $order = &$orderList[$vo['order_code']];
            $vo['img_url'] = getImageUrl($vo['img']);
            unset($vo['img']);
            if(!empty($order)){
                array_push($order['_items'],$vo);
            }
        }

        return $orderList;
    }

    private function getMapFromResult(&$list){

        $newList = array();

        $mapItem = array();

        foreach($list as $vo){
            array_push($mapItem,$vo['order_code']);
            $newList[$vo['order_code']] = $vo;
            $newList[$vo['order_code']]['_items'] = array();
        }
        $list = $newList;
        return array('order_code'=>array('in',$mapItem));
    }

    /**
     * 查看订单详情
     */
    public function detail(){
        $notes = "应用".$this->client_id.",调用查询订单详情接口";
        addLog("Orders/detail",$_GET,$_POST,$notes);
        $id=I('post.id',0); //订单ID
        if($id==0){
            $this->apiReturnErr("缺少订单ID");
        }
        $map=array(
            'id'=>$id,
        );
        $result=apiCall(OrdersInfoViewApi::GET_INFO,array($map));




        if($result['status']){

            $order=$result['info'];

            if(is_null($order)){
                $this->apiReturnErr("获取失败,没有此订单!");
            }

            $order['store_logo_url'] = getImageUrl($order['store_logo']);

            $map=array(
                'order_code'=>$order['order_code'],
            );
            $result=apiCall(OrdersItemApi::QUERY_NO_PAGING,array($map));
            if($result['status']){
                $order['items'] = $result['info'];

                $order['items'] = $this->convertDetail($result['info']);

            }else {
                $this->apiReturnErr("查询中发生错误，请联系相关人员");
            }

            $this->apiReturnSuc($order);
        }else{
            $this->apiReturnErr("查询中发生错误，请联系相关人员");
        }
    }

    /**
     * 获取订单物流信息
     */
    public function express(){

        $order_code = $this->_post("order_code","","订单编号缺失!");

        $result = apiCall(OrdersExpressApi::GET_INFO,array(array('order_code'=>$order_code)));
        $this->checkApiCallResult($result,true,"发货信息获取失败!");

        $this->apiReturnSuc($result['info']);

    }


    /**
     * Convert
     * @param $order_list
     * @return mixed
     */
    private function convertDetail($list){
        foreach($list as &$vo) {
            $vo['img_url'] = getImageUrl($vo['img']);
        }
        return $list;
    }




    function getSupportMethod(){

    }
}

